import { Injectable } from '@angular/core';
import { NativeService } from './NativeService';
import { ApiService } from './ApiService';
import { Storage } from '@ionic/storage';
import { Camera } from '@ionic-native/camera';
import { ActionSheetController,ToastController} from 'ionic-angular';


@Injectable()
export class EditorService {
  savedRange;
  isInFocus;
  token;
  constructor(
    private apiService: ApiService,
    private NativeService: NativeService,
    public toastCtrl: ToastController,
    public storage: Storage,
  public actionSheetCtrl: ActionSheetController
  ){

  }
  ionViewDidEnter(){
    this.storage.get('mytoken').then((mytoken)=>{
      if(mytoken) {
        this.token = mytoken;
      }
    })
  }
  private dismissHandler() {
    //console.info('Toast onDidDismiss()');
  }

  //消息提示函数
  formTip(hint){
    const toast = this.toastCtrl.create({
      message: hint,
      duration: 3000,
      position: 'middle'
    });
    toast.onDidDismiss(this.dismissHandler);
    toast.present();
    return;
  }
  saveSelection() {
    if(window.getSelection) {
      this.savedRange = window.getSelection().getRangeAt(0);
    }
  }
  restoreSelection() {
    this.isInFocus = true;
    let editableContent = document.getElementById("editor");
    editableContent.focus();
    if (this.savedRange != null) {
      if (window.getSelection) {
        var s = window.getSelection();
        if (s.rangeCount > 0) {
          s.removeAllRanges();
        } else {
          s.addRange(this.savedRange);
        }
      } else if (document.createRange) {
        window.getSelection().addRange(this.savedRange);
      }
    }
  }

  insertImage(imageName, imagePath) {
    this.restoreSelection();
    let imageElement = document.createElement('img');
    let breakElement = document.createElement('div');
    imageElement.setAttribute('src', imagePath);
    imageElement.setAttribute('id', imageName);
    breakElement.innerHTML = "<br>";
    let editableContent = document.getElementById("editor");
    editableContent.appendChild(imageElement);
    editableContent.appendChild(breakElement);
  }

  clickUploadImgBtn(token) {
    console.log(token)
    let actionSheet = this.actionSheetCtrl.create({
      title: '选择图片',
      buttons: [{text: '从相册选取', handler: () => {
        this.NativeService.getPictureByPhotoLibrary({ targetWidth: 562.5, targetHeight: 421.5 }).then(imageBase64 => {
          this.apiService.uploadImgs({token:token,img_base64: 'data:image/jpeg;base64,' + imageBase64}, response =>{
            if(response.json().status == 1){
              this.formTip('图片上传成功！');
              this.insertImage('images-0', response.json().content)
            }else{
              this.formTip(response.json().info)
            }
          })
        })
      }}, {text: '拍照', handler: () => {
        this.NativeService.getPictureByCamera({ targetWidth: 562.5, targetHeight: 421.5 }).then(imageBase64 => {
          this.apiService.uploadImgs({token:token,img_base64:'data:image/jpeg;base64,'+imageBase64}, response =>{
            if(response.json().status == 1){
              this.formTip('图片上传成功！');
              this.insertImage('images-0', response.json().content)
            }else{
              this.formTip(response.json().info)
            }
          })
        })
      }}, {
        text: '取消',
        role: 'cancel',
        handler: () => {
          console.log('Cancel clicked');
        }
      }]
    });
    actionSheet.present();
  }
}
